﻿using Kingdee.BOS;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.K3.Core.Mobile.Utils;
using Kingdee.BOS.Model.ReportFilter;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using Kingdee.BOS.Util;
using Kingdee.BOS.App.Data;
using System.ComponentModel;


namespace Fibot.YGJD.K3Cloud.SAL.Business.PlugIn
{
    [HotUpdate]
    [Description("销售出库 获取应收单余额")]
    public class OutStockEdit : AbstractBillPlugIn
    {

        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);

            string fieldKey = e.Field.Key;

            if (fieldKey.EqualsIgnoreCase("FCustomerID"))
            {
                var newValue = Convert.ToInt32(e.NewValue);
                if (newValue <= 0)
                {
                    this.View.Model.SetValue("F_UIXC_AMOUNT3", 0);
                    this.View.UpdateView("F_UIXC_AMOUNT3");
                    return;
                }
                string reportFormId = "AR_SumReport";
                string filterFormId = "AR_SumRepFilter";
                Dictionary<string, string> dicFilter = new Dictionary<string, string>();
                var orgIdObj = this.View.Model.GetValue("FSaleOrgId") as DynamicObject;
                dicFilter.Add("SettleOrgLst", orgIdObj["Id"].TryPareValue<string>());
                dicFilter.Add("BeginDate", DateTime.Now.ToString("yyyy-MM-dd"));
                dicFilter.Add("EndDate", DateTime.Now.ToString("yyyy-MM-dd"));
                dicFilter.Add("FUSEDATE", "1");
                dicFilter.Add("FDateRadioGrp", "1");
                dicFilter.Add("FSTARTYEAR", DateTime.Now.Year.ToString());
                dicFilter.Add("FENDYEAR", DateTime.Now.Year.ToString());
                dicFilter.Add("FSTARTPERIOD", DateTime.Now.Month.ToString());
                dicFilter.Add("FENDPERIOD", DateTime.Now.Month.ToString());
                dicFilter.Add("CONTACTUNITFrom_Id", newValue.ToString());
                dicFilter.Add("CONTACTUNITTo_Id", newValue.ToString());

                string filterSchemeSql = $"/*dialect*/SELECT FSCHEMEID FROM T_BAS_FILTERSCHEME where FFORMID = '{filterFormId}' and FSCHEMENAME = 'Default Scheme'";




                DynamicObjectCollection filterSchemeCollection = DBUtils.ExecuteDynamicObject(this.Context, filterSchemeSql);
                string schemeId = "";
                if (filterSchemeCollection.Count > 0)
                {
                    schemeId = filterSchemeCollection[0]["FSCHEMEID"].ToString();
                }
                DataTable dt = GetReportData(Context, reportFormId, filterFormId, dicFilter, schemeId);

                int i = 0;
                if (dt != null && dt.Rows.Count > 0)
                {

                    try
                    {
                        var row = dt.Select($" fcustid = '{newValue}' and fsettleorgid = '{orgIdObj["Id"].TryPareValue<string>()}' ");

                        if (row.Length > 0)
                        {
                            this.View.Model.SetValue("F_UIXC_Amount", Convert.ToDecimal(row[0]["FLEFTAMOUNT"]));
                            this.View.UpdateView("F_UIXC_Amount");
                        }
                    }
                    catch (Exception ex)
                    {

                    }
                }

            }

        }


        /// <summary>
        /// https://vip.kingdee.com/article/337264184725122048?productLineId=1&lang=zh-CN
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="reportFormId"></param>
        /// <param name="filterFormId"></param>
        /// <param name="dicFilter"></param>
        /// <param name="schemeId"></param>
        /// <returns></returns>
        private DataTable GetReportData(Context ctx, string reportFormId, string filterFormId, Dictionary<string, string> dicFilter, string schemeId)
        {
            try
            {
                ISysReportService sysReporSservice = ServiceFactory.GetSysReportService(ctx);
                IPermissionService permissionService = ServiceFactory.GetPermissionService(ctx);
                var filterMetadata = FormMetaDataCache.GetCachedFilterMetaData(ctx);//加载字段比较条件元数据。
                var reportMetadata = FormMetaDataCache.GetCachedFormMetaData(ctx, reportFormId);//加载对账报表元数据。
                var reportFilterMetadata = FormMetaDataCache.GetCachedFormMetaData(ctx, filterFormId);//加载对账报表过滤条件元数据。
                var reportFilterServiceProvider = reportFilterMetadata.BusinessInfo.GetForm().GetFormServiceProvider();
                var model = new SysReportFilterModel();
                model.SetContext(ctx, reportFilterMetadata.BusinessInfo, reportFilterServiceProvider);
                model.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
                model.FilterObject.FilterMetaData = filterMetadata;
                model.InitFieldList(reportMetadata, reportFilterMetadata);
                model.GetSchemeList();
                model.LoadDefaultScheme();//.Load(schemeId);//过滤方案的主键值，可通过该SQL语句查询得到：SELECT * FROM T_BAS_FILTERSCHEME
                var filter = model.GetFilterParameter();
                DynamicObject filterObj = filter.CustomFilter;

                foreach (var item in dicFilter)
                {
                    if (filterObj.Contains(item.Key))
                    {
                        filterObj[item.Key] = item.Value;
                    }
                }

                IRptParams p = new RptParams();
                p.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
                p.StartRow = 1;
                p.EndRow = 50000;//StartRow和EndRow是报表数据分页的起始行数和截至行数，一般取所有数据，所以EndRow取int最大值。
                p.FilterParameter = filter;
                p.FilterFieldInfo = model.FilterFieldInfo;
                p.BaseDataTempTable.AddRange(permissionService.GetBaseDataTempTable(ctx, reportMetadata.BusinessInfo.GetForm().Id));

                p.CustomParams.Add("OpenParameter", "");//此参数不能缺少，即使为空也要保留
                p.FilterParameter.GroupbyString = "";

                MoveReportServiceParameter reportServiceParam = new MoveReportServiceParameter(ctx, reportMetadata.BusinessInfo, Guid.NewGuid().ToString(), p);
                IReportData result = sysReporSservice.GetReportData(reportServiceParam);
                ServiceFactory.CloseService(sysReporSservice);
                ServiceFactory.CloseService(permissionService);
                return result.DataSource;
            }
            catch (Exception ex)
            {

            }
            return null;
        }


    }
}
